package com.kinoshita.manager.service.impl;

import com.kinoshita.admin.api.client.AdminClient;
import com.kinoshita.admin.api.domain.AdminDO;
import com.kinoshita.common.result.ResultDO;
import com.kinoshita.common.status.Constant;
import com.kinoshita.common.status.StatusCode;
import com.kinoshita.manager.api.domain.UserLoginSuccessDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class AdminUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminClient adminClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException(StatusCode.USER_NAME_NOT_NULL.getMsg());
        }
        ResultDO resultDO = adminClient.getAdminByName(username);
        if(!resultDO.isSuccess()) {
            throw new UsernameNotFoundException(StatusCode.USER_IS_NO_EXIST.getMsg());
        }
        AdminDO domain = (AdminDO) resultDO.getModel(Constant.DATA_MODEL_KEY);
        UserLoginSuccessDO userLoginSuccessDO = new UserLoginSuccessDO(domain.getId(), domain.getUsername(), domain.getPassword());
        return userLoginSuccessDO;
    }
}
